<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Skin_model extends CI_Model {


	public function accesoUser($id_articulo)
	{
		$res = $this->db->query("SELECT
			isValidTicAccess(".$this->session->userdata('id_usuario').", ".$id_articulo.") AS acce")->row();
		return json_decode($res->acce);
	}

	public function getAsesoriaVenta(){
		$res = $this->db->query("SELECT * FROM asesoria_ventas WHERE id = 1")->row();
		return $res;
	}

	public function registraVisita($id_usuario, $id_articulo, $idunico){
		if($idunico != ''){
			$res_s = $this->db->query("SELECT Count(*) AS visita FROM articulos_visitas
				WHERE id_articulo = ".$id_articulo." AND id_usuario = ".$id_usuario."
					AND idunico = '".$idunico."' AND Date(fecha) = Date(Now())")->row();
			if($res_s->visita == 0){
				$this->db->insert('articulos_visitas',
					array(
						'id_articulo' => $id_articulo,
						'id_usuario'  => $id_usuario,
						'idunico'     => $idunico,
						'es_tic'      => ($this->session->userdata('tipo')=='tic'? 1: 0)
						));
			}
		}
	}



	/************************
	* Accesi tic
	*/
	public function getInfografias($per_pag='6'){
		$sql = '';
		//paginacion
		$this->load->library('pagination');
		$params = array(
				'result_items_per_page' => $per_pag,
				'result_page' => (isset($_GET['pag'])? $_GET['pag']: 0)
		);
		if($params['result_page'] % $params['result_items_per_page'] == 0)
			$params['result_page'] = ($params['result_page']/$params['result_items_per_page']);

		//Filtros para buscar
		$sql   .= ($this->input->get('fbuscar') != ''?
			" AND (UPPER(ai.titulo) LIKE '%".mb_strtoupper($this->input->get('fbuscar'), 'utf-8')."%'
					OR UPPER(ai.tags) LIKE '%".mb_strtoupper($this->input->get('fbuscar'), 'utf-8')."%')": '');
		$sql   .= ($this->input->get('ftipo') != ''? " AND tipo LIKE '".$this->input->get('ftipo')."'": '');

		$query = BDUtil::pagination("
			SELECT ai.id_imagen, ai.url, ai.url_thumb, ai.titulo, ai.tags, IFNULL( aif.id_usuario,  'no' ) AS favorito
			FROM articulos_imagenes AS ai
				LEFT JOIN articulos_imagenes_favoritas AS aif ON ( ai.id_imagen = aif.id_imagen
					AND aif.id_usuario = ".$this->session->userdata('id_usuario')." ) 
			WHERE ai.status =0 ".$sql."
			ORDER BY ai.id_imagen DESC", $params, true);
		$res = $this->db->query($query['query']);

		$response = array(
				'infogramas'      => array(),
				'total_rows'     => $query['total_rows'],
				'items_per_page' => $params['result_items_per_page'],
				'result_page'    => $params['result_page']
		);
		if($res->num_rows() > 0)
			$response['infogramas'] = $res->result();

		return $response;
	}


	public function getCarrito(){
		$response = array();
		$data = $this->db->query("SELECT a.id_articulo, a.titulo, at.nombre, pc.costo
			FROM paquetes_carrito AS pc
				INNER JOIN articulos AS a ON a.id_articulo = pc.id_articulo
				INNER JOIN articulos_tipo AS at ON a.id_tipo = at.id_tipo
			WHERE pc.id_usuario = ".$this->session->userdata('id_usuario')."
			ORDER BY a.titulo ASC");
		$response = $data->result();
		return $response;
	}
	public function addCarrito(){
		$data = $this->db->query("SELECT a.id_articulo, p.precio
		FROM articulos AS a
			INNER JOIN precios AS p
		WHERE a.id_articulo = ".$this->input->post('id')."
			AND p.tipo = CONCAT(  'artic-', a.id_tipo ) ")->row();

		if (isset($data->precio)) {
			$this->db->insert('paquetes_carrito', array(
				'id_articulo' => $this->input->post('id'),
				'id_usuario'  => $this->session->userdata('id_usuario'),
				'costo'       => $data->precio
				));
			return 1;
		}

		return 2;
	}
	public function quitCarrito(){
		$this->db->delete('paquetes_carrito', array(
			'id_articulo' => $this->input->get('id'),
			'id_usuario'  => $this->session->userdata('id_usuario')
			) );
	}


	public function getPublicidad($acc_ilim){
		$response = array();
		$data = $this->db->query("SELECT * FROM publicidad ORDER BY id ASC");
		$data = $data->result();

		if ($this->session->userdata('acceso')=='institucion') {
			$response = array('nombre' => $data[1]->nombre,
				'pags' => array(
						$data[1]->pag1,
						$data[1]->pag2,
						$data[1]->pag3
					));
		}elseif($acc_ilim->paquete == 0){
			$response = array('nombre' => $data[0]->nombre,
				'pags' => array(
						$data[0]->pag1,
						$data[0]->pag2,
						$data[0]->pag3
					));
		}else{
			if($acc_ilim->meses < 3){ //el de 1 mes
				$idx = 2;
			}elseif($acc_ilim->meses < 6){
				$idx = 3;
			}elseif($acc_ilim->meses < 12){
				$idx = 4;
			}else{
				$idx = 5;
			}

			$response = array('nombre' => $data[$idx]->nombre,
				'pags' => array(
						$data[$idx]->pag1,
						$data[$idx]->pag2,
						$data[$idx]->pag3
					));
		}

		return $response;
	}

  /**
   * Carga los mensajes del chat del usuario tic logueado
   * @return [type] [description]
   */
  public function ajax_carga_mensajes()
  {
    $id_usuario = $this->session->userdata('id_usuario');

    $query_res = $this->db->query("SELECT ibox.id_msg, ibox.id_usuario, ibox.mensaje, ibox.fecha, ibox.alerta, iboxr.id_usuario AS usuario_res
                                    FROM inbox ibox
                                    LEFT JOIN inbox_respuestas iboxr ON iboxr.id_msg = ibox.id_msg
                                    WHERE ibox.id_usuario = ".$id_usuario."
                                    OR iboxr.id_usuario = ".$id_usuario."
                                    ORDER BY ibox.fecha ASC");

    return $query_res->result();
  }

  // Envia el mensaje del usuario
  public function envia_mensaje()
  {
    $data = array('id_usuario'=>$this->session->userdata("id_usuario"), 'mensaje'=> nl2br($_POST['mensaje']));
    $this->db->insert('inbox', $data);

    $result = $this->get_total_mensajes_pendientes(TRUE);
    if (count($result) > 0)
    {
      foreach ($result as $msg) {
        $this->db->update('inbox', array('alerta'=>0), array('id_msg'=>$msg->id_msg));
      }
    }

    return TRUE;
  }

  public function get_total_mensajes_pendientes($return_result = FALSE)
  {
    $id_usuario = $this->session->userdata('id_usuario');
    $result = $this->db->query("SELECT i.id_msg
                                FROM inbox i
                                INNER JOIN inbox_respuestas ir ON ir.id_msg = i.id_msg
                                WHERE ir.id_usuario = ".$id_usuario."
                                AND i.alerta = 1");

    if ($return_result)
      return $result->result();

    $total = 0;
    if ($result->num_rows() > 0 )
      $total = $result->num_rows();

    return $total;
  }



  /********* confirmar pago de compra ************/
  public function doPayment($id_paquete){
  	// $id_paquete = $this->input->get('n');
  	
  	if (count(explode(',', $id_paquete)) > 1) { //son varios paquetes a comprar
  		$res = $this->db->query("SELECT id_paquete, IF(tipo='todo', 'Acceso ilimitado', 'Arma tu paquete') AS tipo,
					costo AS precio, meses, tipo AS tipo2, (SELECT COUNT(*) FROM paquetes_articulos WHERE id_paquete = paquetes.id_paquete) AS articulos
				FROM paquetes WHERE status = 0 AND id_paquete IN (".$id_paquete.")
					AND id_usuario = ".$this->session->userdata('id_usuario'))->result_array();
			foreach($res as $key => $itm){
				$itm['titulo'] = ($itm['tipo2']=='todo'?
				$itm['meses'].($itm['meses']==1? ' mes': ' meses'):
				$itm['articulos'].($itm['articulos']==1? ' publicación': ' publicaciones'));
				$res[$key] = $itm;
			}
			$datapa = $res;
  	}else{ // es solo un paquete
			$datap = $this->db->query("SELECT * FROM paquetes WHERE id_paquete = ".$id_paquete)->row();
			if ($datap->tipo == 'segmento') {
				$datapa = $this->db->query("SELECT a.id_articulo, a.titulo, a.numero, p.precio
					FROM articulos AS a
						INNER JOIN paquetes_articulos AS pa ON a.id_articulo = pa.id_articulo
						INNER JOIN precios as p
					WHERE pa.id_paquete = ".$id_paquete." AND p.tipo = CONCAT('artic-', a.id_tipo)")->result_array();
			}else{
				$meses      = $datap->meses;
				$datapa[0]  = array('id_articulo' => '', 'titulo' => '', 'numero' => '1', 'precio' => '');
				$dataprecio = $this->db->query("SELECT precio FROM precios WHERE tipo = 'ilim-".intval($meses)."'")->row();

				switch ($meses) {
					case 1:
						$datapa[0]['titulo'] = '1 mes de Acceso ilimitado';
						$datapa[0]['precio'] = $dataprecio->precio;
						break;
					case 3:
						$datapa[0]['titulo'] = '3 meses de Acceso ilimitado';
						$datapa[0]['precio'] = $dataprecio->precio;
						break;
					case 6:
						$datapa[0]['titulo'] = '6 meses de Acceso ilimitado';
						$datapa[0]['precio'] = $dataprecio->precio;
						break;
					case 12:
						$datapa[0]['titulo'] = '12 meses de Acceso ilimitado';
						$datapa[0]['precio'] = $dataprecio->precio;
						break;
				}
			}
		}

		$total = 0;

		// Include required library files.
		require_once(APPPATH.'libraries/paypal/config.php');
		require_once(APPPATH.'libraries/paypal/paypal.class.php');

		$PayPalConfig = array('Sandbox' => $sandbox, 'APIUsername' => $api_username, 'APIPassword' => $api_password, 'APISignature' => $api_signature);
		$PayPal = new PayPal($PayPalConfig);

		// Prepare request arrays
		$DECPFields = array(
							'token' => $this->input->get('token'), 								// Required.  A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
							'payerid' => $this->input->get('PayerID'), 							// Required.  Unique PayPal customer id of the payer.  Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL.
							'returnfmfdetails' => '', 					// Flag to indiciate whether you want the results returned by Fraud Management Filters or not.  1 or 0.
							'giftmessage' => '', 						// The gift message entered by the buyer on the PayPal Review page.  150 char max.
							'giftreceiptenable' => '', 					// Pass true if a gift receipt was selected by the buyer on the PayPal Review page. Otherwise pass false.
							'giftwrapname' => '', 						// The gift wrap name only if the gift option on the PayPal Review page was selected by the buyer.
							'giftwrapamount' => '', 					// The amount only if the gift option on the PayPal Review page was selected by the buyer.
							'buyermarketingemail' => '', 				// The buyer email address opted in by the buyer on the PayPal Review page.
							'surveyquestion' => '', 					// The survey question on the PayPal Review page.  50 char max.
							'surveychoiceselected' => '',  				// The survey response selected by the buyer on the PayPal Review page.  15 char max.
							'allowedpaymentmethod' => '' 				// The payment method type. Specify the value InstantPaymentOnly.
						);
		
		$Payments = array();
		$Payment = array(
						'amt' => '0.00', 							// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
						'currencycode' => 'MXN', 					// A three-character currency code.  Default is USD.
						'itemamt' => '0.00', 						// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
						'shippingamt' => '0.00', 					// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
						'shippingdiscamt' => '', 				// Total shipping discount for this order, specified as a negative number.
						'insuranceoptionoffered' => '', 		// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
						'handlingamt' => '', 					// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
						'taxamt' => '0.00', 						// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
						'desc' => 'This is a test order', 							// Description of items on the order.  127 char max.
						'custom' => '', 						// Free-form field for your own use.  256 char max.
						'invnum' => '', 						// Your own invoice or tracking number.  127 char max.
						'notifyurl' => '', 						// URL for receiving Instant Payment Notifications
						'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
						'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
						'shiptostreet2' => '', 					// Second street address.  100 char max.
						'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
						'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
						'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
						'shiptocountrycode' => '', 				// Required if shipping is included.  Country code of shipping address.  2 char max.
						'shiptophonenum' => '',  				// Phone number for shipping address.  20 char max.
						'notetext' => 'This is a test note before ever having left the web site.', 						// Note to the merchant.  255 char max.  
						'allowedpaymentmethod' => '', 			// The payment method type.  Specify the value InstantPaymentOnly.
						'paymentaction' => 'Sale', 					// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order. 
						'paymentrequestid' => '',  				// A unique identifier of the specific payment request, which is required for parallel payments. 
						'sellerpaypalaccountid' => '', 			// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
						'sellerid' => '', 						// The unique non-changing identifer for the seller at the marketplace site.  This ID is not displayed.
						'sellerusername' => '', 				// The current name of the seller or business at the marketplace site.  This name may be shown to the buyer.
						'sellerregistrationdate' => '', 		// Date when the seller registered at the marketplace site.
						'softdescriptor' => ''					// A per transaction description of the payment that is passed to the buyer's credit card statement.
						);

		$PaymentOrderItems = array();
		foreach ($datapa as $key => $value) {
			$Item = array(
					'name' => $value['titulo'], 							// Item name. 127 char max.
					'desc' => '', 							// Item description. 127 char max.
					'amt' => String::float($value['precio']), 								// Cost of item.
					'number' => '', 							// Item number.  127 char max.
					'qty' => '1', 								// Item qty on order.  Any positive integer.
					'taxamt' => '', 							// Item sales tax
					'itemurl' => '', 							// URL for the item.
					'itemweightvalue' => '', 					// The weight value of the item.
					'itemweightunit' => '', 					// The weight unit of the item.
					'itemheightvalue' => '', 					// The height value of the item.
					'itemheightunit' => '', 					// The height unit of the item.
					'itemwidthvalue' => '', 					// The width value of the item.
					'itemwidthunit' => '', 					// The width unit of the item.
					'itemlengthvalue' => '', 					// The length value of the item.
					'itemlengthunit' => '',  					// The length unit of the item.
					'ebayitemnumber' => '', 					// Auction item number.
					'ebayitemauctiontxnid' => '', 			// Auction transaction ID number.
					'ebayitemorderid' => '',  				// Auction order ID number.
					'ebayitemcartid' => ''					// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
					);
			$total += $Item['amt'];
			array_push($PaymentOrderItems, $Item);
		}

		$Payment['amt']         = $total;
		$Payment['itemamt']     = $total;

		$Payment['order_items'] = $PaymentOrderItems;
		array_push($Payments, $Payment);

		$UserSelectedOptions = array(
							 'shippingcalculationmode' => '', 	// Describes how the options that were presented to the user were determined.  values are:  API - Callback   or   API - Flatrate.
							 'insuranceoptionselected' => '', 	// The Yes/No option that you chose for insurance.
							 'shippingoptionisdefault' => '', 	// Is true if the buyer chose the default shipping option.  
							 'shippingoptionamount' => '', 		// The shipping amount that was chosen by the buyer.
							 'shippingoptionname' => '', 		// Is true if the buyer chose the default shipping option...??  Maybe this is supposed to show the name..??
							 );
							 
		$PayPalRequestData = array(
							   'DECPFields' => $DECPFields, 
							   'Payments' => $Payments, 
							   'UserSelectedOptions' => $UserSelectedOptions
							   );

		// Pass data into class for processing with PayPal and load the response array into $PayPalResult
		$PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData);
		return $PayPalResult;
	}


}

/* End of file articulos_model.php */
/* Location: ./application/models/articulos_model.php */
